package com.youku.util;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import com.youku.exception.JsonNodeMissingException;

/**
 * json处理的工具类
 * 
 * @author loda
 *
 */
public class JsonHelper {

	private static final ObjectMapper mapper;

	static {
		mapper = new ObjectMapper();
	}

	public static String toJsonString(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static String path(JsonNode root, String path) {
		JsonNode n = root;

		boolean isSize = false;

		if (StringUtils.endsWith(path, ".size")) {
			isSize = true;
			path = path.substring(0, path.length() - 5);
		}

		String[] fields = StringUtils.split(path, "/");

		StringBuilder errorMsg = new StringBuilder();

		for (String p : fields) {
			if (n.isMissingNode()) {
				StringHelper.deleteTokenIfEndWith(errorMsg, "/");
				throw new JsonNodeMissingException("该节点找不到:" + errorMsg.toString());
			}
			errorMsg.append(p).append('/');
			if (isNumber(p)) {
				// 在配置时下标从1开始，转到程序中就要将获取到的下标index-1
				int index = Integer.parseInt(p) - 1;
				if (index < 0) {
					StringHelper.deleteTokenIfEndWith(errorMsg, "/");
					throw new JsonNodeMissingException("找不到第" + p + "个位置的元素:" + errorMsg.toString());
				}
				n = n.path(index);
			} else {
				n = n.path(p);
			}
		}
		if (n.isMissingNode()) {
			StringHelper.deleteTokenIfEndWith(errorMsg, "/");
			throw new JsonNodeMissingException("该节点找不到:" + errorMsg.toString());
		}

		if (isSize) {
			if (n.isArray()) {
				return String.valueOf(n.size());
			} else {
				throw new IllegalArgumentException(".size属性只能使用在array类型的json元素上");
			}
		} else {
			return n.asText();
		}

	}

	public static JsonNode parse(String json) throws IOException {
		return mapper.readTree(json);
	}

	private static boolean isNumber(String s) {
		if (s == null)
			return false;
		return s.matches("\\d+");
	}
}
